package sever

import (
	study "0411zk/common/proto"
	"0411zk/pkg"
	"0411zk/rpc/models"
	"fmt"
	"strconv"
)

func UserRegister(req *study.UserRegisterReq) (*study.UserRegisterResp, error) {
	u := models.User{}
	mobile, err := u.FindUserMobile(req.Mobile)

	if mobile != nil {
		return nil, fmt.Errorf("注册失败,用户已被注册")
	}

	user, err := u.CreateUser(req)
	if err != nil {
		return nil, err
	}

	return &study.UserRegisterResp{
		UserId: int64(user.ID),
	}, nil

}

func BrowseCourses(req *study.BrowseCoursesReq) (*study.BrowseCoursesResp, error) {
	c := models.Course{}
	list, err := c.FindCoursesList()
	if err != nil {
		return nil, err
	}
	var all []*study.BrowseCoursesList

	for _, i := range list {
		all = append(all, &study.BrowseCoursesList{
			CoursesId: int64(i.ID),
			Name:      i.Name,
			Price:     float32(i.Price),
			Stock:     i.Stock,
		})
	}
	return &study.BrowseCoursesResp{
		List: all,
	}, nil

}
func BrowseCoursesAdd(req *study.BrowseCoursesAddReq) (*study.BrowseCoursesAddResp, error) {
	s := models.StudyPlan{}
	_, err := s.CreateCourse(req)
	if err != nil {
		return nil, fmt.Errorf("添加课程失败")
	}
	return &study.BrowseCoursesAddResp{
		Success: true,
	}, err

}
func BrowseCoursesDel(req *study.BrowseCoursesDelReq) (*study.BrowseCoursesDelResp, error) {
	s := models.StudyPlan{}
	_, err := s.DelCourse(req)
	if err != nil {
		return nil, fmt.Errorf("删除课程失败")
	}
	return &study.BrowseCoursesDelResp{
		Success: true,
	}, err
}
func CoursesOrder(req *study.CoursesOrderReq) (*study.CoursesOrderResp, error) {
	c := models.CourseOrder{}

	cour := models.Course{}

	//c2 := &models.Coupon{}

	//coupon, err := c2.FindCoupon(req.UserId)
	//if err != nil {
	//	return nil, fmt.Errorf("优惠卷查询失败")
	//}

	courses, err := cour.FindCourses(req.CoursesId)
	if err != nil {
		return nil, fmt.Errorf("课程查询失败")
	}

	order, err := c.CreateOrder(req, courses)
	if err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}

	float := strconv.FormatFloat(order.Price, 'f', -1, 64)

	alipay := pkg.Alipay(cour.Name, order.OrderSn, float)

	return &study.CoursesOrderResp{
		OrderId: int64(order.ID),
		Url:     alipay,
	}, nil

}
